﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KMS.Core
{
    public partial class ServiceBase<T>
    {
        protected virtual bool OnBeforeUpdateEntity(UpdateEventArgs arg)
        {
            return true;
        }

        protected virtual void OnAfterUpdateEntity(UpdateEventArgs arg)
        {

        }
        public int Update(T model)
        {
            var result = 0;
            QueryExcute(
                db =>
                {
                    var rtnBefore = this.OnBeforeUpdateEntity(new UpdateEventArgs() { Db = db, Data = model });
                    if (!rtnBefore)
                    {
                        return;
                    }
                     result= db.UpdateEntity(model);
                     this.OnAfterUpdateEntity(new UpdateEventArgs() { Db = db, Data = model, ExecuteValue = result });
                });
          
            return result;
        }

        public int Update(UpdateQuery<T> query, Func<DeleteEventArgs, bool> beforeEvent = null, Action<DeleteEventArgs> afterEvent = null)
        {
            var result = 0; 
            QueryExcute(
                db =>
                {
                    if (beforeEvent != null)
                    {
                        var rtnBefore = beforeEvent(new DeleteEventArgs() { Db = db, Data = query });
                        if (!rtnBefore)
                        {
                            return;
                        }
                    }

                    result = db.UpdateQuery(query);
                    if (afterEvent != null)
                    {
                        afterEvent(new DeleteEventArgs() { Db = db, Data = query, ExecuteValue = result });
                    }
                }
             );
            return result;
        }
    }
}
